package com.example.administrator.demo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.example.administrator.demo.util.AuthResult;
import com.example.administrator.demo.util.OrderInfoUtil2_0;

import java.util.Map;


public class MainActivity extends AppCompatActivity {
   private Button login;

    private int LoginType = -1;
    //支付宝账户登录授权业务：入参pid值

   private static String pid="2088221943292400";
    public static String kAlipay_APPID = "2017102709555219";
    public static final String RSA2_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC4YuTdNU+u6c83ejvI+DGD3U16Q3ffU0ocz+zsTVpOaDUvHvJBIljICbwSrLnbViilL+7btZo2j/UzdMGIg1Br6KeeSWiATXJPf4Xb5bXtuoYuYayZyXUEWpEN/+X5cZoc3aZVgjzfR+6pnVEeQKZcxWJRMcxvulPIAPURfrUJ5AwqgE8ftmhnY4+TnLstxtveX6vZdzlf4+UJ13NC2G6kfFfYHPGj+te25xwjv+EhUpO8uL6J9L4BG5zqBG5TV8FiIdnEvZ9SzGm7fj4CmzI4TBPlXmVhMVYa1HSySBCdJdS96SzULXr7XhQ3klCKTNVwvrCSETJr1duzt8sllkjlAgMBAAECggEAQ+w6Prq6xcZfjSI8D8ZOBzNorRdZey0lagO2VT4RfDyrCtatiwzqA5aCb6atOH0+r8s+hDUbv+m7+96QxIcLAxVLWeXU1x6wc1SYrO6r3A0QDNnySRyLPLVYJf4Ua5VLnkKQWYOGhQHsixLmpOxP3HDhzOM5WhcbcdvYaz9v1VpKWBrpNcosZ1tdH0jbutkpRKp0fNJn2vkDa6fcB0uZWKSHFWX04lbDxgOXnTkvz/wXQgpy195gUVvS3hWjFY6VJx8K+qQD1rlnbUuHIx7yP9Mo7IPrsPBqkXg59d7Ie18vjgAu21IIDcIv+mxhYShdXn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cl1BFqRDf/l+XGaHN2mVYI830fuqZ1RHkCmXMViUTHMb7pTyAD1EX61CeQMKoBPH7ZoZ2OPk5y7Lcbb3l+r2Xc5X+PlCddzQthupHxX2Bzxo/rXtuccI7/hIVKTvLi+ifS+ARuc6gRuU1fBYiHZxL2fUsxpu34+ApsyOEwT5V5lYTFWGtR0skgQnSXUveks1C16+14UN5JQikzVcL6wkhEya9Xbs7fLJZZI5QIDAQAB\n";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(MainActivity.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(MainActivity.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        login=findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(kAlipay_APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
                    new AlertDialog.Builder(MainActivity.this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialoginterface, int i) {
                                }
                            }).show();
                    return;
                }

                /**
                 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
                 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
                 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
                 *
                 * orderInfo的获取必须来自服务端；
                 */
                boolean rsa2 = (RSA2_PRIVATE.length() > 0);
                Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(kAlipay_APPID, rsa2);
                String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
                String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
                String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
                final String orderInfo = orderParam + "&" + sign;
                Map<String, String> stringStringMap = OrderInfoUtil2_0.buildAuthInfoMap(pid, kAlipay_APPID, "1233", rsa2);
                String orderParam2 = OrderInfoUtil2_0.buildOrderParam(stringStringMap);
                String privateKey2 = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
                String sign2 = OrderInfoUtil2_0.getSign(params, privateKey2, rsa2);
                final String orderInfo2 = orderParam2 + "&" + sign2;
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {

                        AuthTask task=new AuthTask(MainActivity.this);
                        Map<String, String> result = task.authV2(orderInfo2, true);

                        Log.i("msp", result.toString());

                        Message msg = new Message();
                        msg.what = SDK_AUTH_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        });
    }
}
